package xyz.lwm.lazycat.web.handle;

import lombok.extern.slf4j.Slf4j;
import xyz.lwm.lazycat.web.exception.ExceptionMapperImpl;

import java.util.List;

/**
 * handler chain
 *
 * @author lwm
 */
@Slf4j
public class HandlerChain implements Handler {

    private final List<Handler> handlers;

    private final ExceptionMapperImpl exceptionMapper;

    public HandlerChain(List<Handler> handlers, ExceptionMapperImpl exceptionMapper) {
        this.handlers = handlers;
        this.exceptionMapper = exceptionMapper;
    }

    @Override
    public void handle(Context ctx) {
        try {
            for (Handler handler : handlers) {
                if (ctx.ended()) {
                    break;
                }
                handler.handle(ctx);
            }
        } catch (Throwable e) {
            exceptionMapper.handle(e, ctx);
            log.error(e.getMessage(), e);
        }
    }

}
